<template>
    <div class="user-plan">
        <div class="user-plan-content">
            <div class="user-plan-info">
                <div class="user-plan-current">
                    <span>当前方案</span>
                    <span class="user-plan-type">{{ currentPlanAlias }}</span>
                </div>
                <div class="user-plan-date" v-if="currentPlanName !== 'free'">
                    <span>有效期至{{ endDate }}</span>
                </div>
                <div class="user-plan-actions">
                    <g-button type="primary" @click="openModal( 'upgrade' )"
                        v-show="planOptions.length !== 0">方案升级</g-button>
                    <g-button type="primary" @click="openModal( 'renewals' )"
                        v-show="currentPlanName !== 'free' && currentPlanName !== 'enterprise'">方案续费</g-button>
                </div>
            </div>
            <div class="user-plan-list">
                <div class="user-plan-header">
                    <div class="user-plan-header-item"><span>数据存储空间</span></div>
                    <div class="user-plan-header-item"><span>数据空间化</span></div>
                    <div class="user-plan-header-item"><span>服务接口调用</span></div>
                    <div class="user-plan-header-item"><span>专享服务</span></div>
                </div>
                <div class="user-plan-item" :class="{ 'current': currentPlanName === 'free' }">
                    <div class="user-plan-item-header">
                        <h3 class="user-plan-item-header-title">{{ plan.free.alias }}</h3>
                        <p class="user-plan-item-header-desc">有一定的资源和服务使用限制，满足一般用户使用。</p>
                        <div class="user-plan-item-header-price">
                            <p class="price-title">方案价格</p>
                            <p class="price-number">￥0</p>
                        </div>
                        <span class="user-plan-item-button-free">免费使用</span>
                    </div>
                    <div class="user-plan-item-info">
                        <div class="user-plan-item-info-item"><span>{{ plan.free.storage }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.free.georeference }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.free.api }}</span></div>
                        <div class="user-plan-item-info-item"><span>无</span></div>
                    </div>
                </div>
                <div class="user-plan-item" :class="{ 'current': currentPlanName === 'standard' }">
                    <div class="user-plan-item-header">
                        <h3 class="user-plan-item-header-title">{{ plan.standard.alias }}</h3>
                        <p class="user-plan-item-header-desc">数据存储无限制，可享受更多服务和资源，满足用户处理业务需要。</p>
                        <div class="user-plan-item-header-price">
                            <p class="price-title">方案价格</p>
                            <p class="price-number">￥{{ plan.standard.month_price }}/月</p>
                        </div>
                        <g-button type="primary" size="large"
                            @click="openModal( 'upgrade', 'standard' )"
                            :disabled="planCompare( 'standard' ) >= 0">
                            {{ planCompare( 'standard' ) === 0 ? '正在使用' : '方案升级' }}
                        </g-button>
                    </div>
                    <div class="user-plan-item-info">
                        <div class="user-plan-item-info-item"><span>{{ plan.standard.storage }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.standard.georeference }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.standard.api }}</span></div>
                        <div class="user-plan-item-info-item"><span>无</span></div>
                    </div>
                </div>
                <div class="user-plan-item" :class="{ 'current': currentPlanName === 'advanced' }">
                    <div class="user-plan-item-header">
                        <h3 class="user-plan-item-header-title">{{ plan.advanced.alias }}</h3>
                        <p class="user-plan-item-header-desc">数据存储无限制，可享受更多服务和资源，满足用户定制开发需要。</p>
                        <div class="user-plan-item-header-price">
                            <p class="price-title">方案价格</p>
                            <p class="price-number">￥{{ plan.advanced.month_price }}/月</p>
                        </div>
                        <g-button type="primary" size="large"
                            @click="openModal( 'upgrade', 'advanced' )"
                            :disabled="planCompare( 'advanced' ) >= 0">
                                {{ planCompare( 'advanced' ) === 0 ? '正在使用' : '方案升级' }}
                        </g-button>
                    </div>
                    <div class="user-plan-item-info">
                        <div class="user-plan-item-info-item"><span>{{ plan.advanced.storage }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.advanced.georeference }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.advanced.api }}</span></div>
                        <div class="user-plan-item-info-item"><span>无</span></div>
                    </div>
                </div>
                <div class="user-plan-item" :class="{ 'current': currentPlanName === 'enterprise' }">
                    <div class="user-plan-item-header">
                        <h3 class="user-plan-item-header-title">{{ plan.enterprise.alias }}</h3>
                        <p class="user-plan-item-header-desc">根据需求享受定制化资源和服务，满足集团型用户需求。</p>
                        <div class="user-plan-item-header-price">
                            <p class="price-title">方案价格</p>
                            <p class="price-number">￥?</p>
                        </div>
                        <g-button type="primary" size="large"
                            @click="openModal( 'concat' )">联系我们</g-button>
                    </div>
                    <div class="user-plan-item-info">
                        <div class="user-plan-item-info-item"><span>{{ plan.enterprise.storage }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.enterprise.georeference }}</span></div>
                        <div class="user-plan-item-info-item"><span>{{ plan.enterprise.api }}</span></div>
                        <div class="user-plan-item-info-item"><span>有</span></div>
                    </div>
                </div>
            </div>
        </div>
        <transition name="g-modal-fade" @afterLeave="afterLeave">
            <div class="g-modal-wrapper private" v-show="modalVisible">
                <div class="g-modal user-plan-modal">
                    <div class="g-modal-header user-plan-modal-header">
                        <span>{{ modalType === 'upgrade' ? '方案升级' : '方案续费' }}</span>
                        <i class="iconfont icon-close" @click="closeModal"></i>
                    </div>
                    <div class="g-modal-content user-plan-modal-content">
                        <div class="user-plan-modal-row" v-show="modalType !== 'renewals'">
                            <span class="user-plan-modal-row-label">选择方案:</span> <g-select 
                            :options="planOptions" v-model="form.plan"></g-select>
                        </div>
                        <div class="user-plan-modal-row" 
                            v-show="modalType === 'renewals' || currentPlanName === 'free'">
                            <span class="user-plan-modal-row-label">{{ modalType === 'renewals' ? '续费时长' : '使用时长' }}:</span>
                            <g-select :options="timeUnitOpions" v-model="form.timeUnit" @input="changeUnit"></g-select>
                            <g-select :options="timeCountOptions" v-model="form.timeCount"></g-select>
                        </div>
                        <div class="user-plan-modal-row">
                            <span class="user-plan-modal-row-label">{{ modalType === 'renewals' ? '续费后' : '' }}到期时间为:</span>
                            <span class="user-plan-modal-end-time">{{ endTime }}</span>
                        </div>
                        <div class="user-plan-modal-row user-plan-row-voucher">
                            <transition name="voucher-fade">
                                <div class="user-plan-modal-voucher" v-show="form.useVoucher">
                                    <g-input placeholder="请输入8位优惠码" v-model="form.voucherId"></g-input>
                                    <g-button @click="checkVoucher" :loading="voucherChecking">验证</g-button>
                                </div>
                            </transition>
                            <label class="user-plan-modal-voucher-label">
                                <input type="checkbox" v-model="form.useVoucher" @input="toggleVoucher"> 使用优惠券
                            </label>
                        </div>

                        <div class="user-plan-modal-row">

                            <div class="user-plan-modal-price-label user-plan-modal-price-label-discount" v-if="form.discount > 0">
                                <span>优惠金额:</span><span class="user-plan-modal-price">{{ form.discount | fixed2 }}</span>
                            </div>

                            <div class="user-plan-modal-price-label user-plan-modal-price-label-amount">
                                <span>应付款:</span><span class="user-plan-modal-price">{{ form.amount | fixed2 }}</span>
                            </div>
                        </div>
                    </div>
                    <form :action="aliPayAction" target="_blank" method="GET" style="display:none;" ref="form">
                        <input type="hidden" name="action" :value="modalType">
                        <input type="hidden" name="type" :value="form.timeUnit">
                        <input type="hidden" name="count" :value="form.timeCount">
                        <input type="hidden" name="product" :value="form.plan">
                        <input type="hidden" name="voucherId" :value="form.voucherId">
                    </form>
                    <div class="g-modal-footer user-plan-modal-footer">
                        <g-button type="primary" size="large" @click="submit" :disabled="payDisable">{{payType}}</g-button>
                    </div>
                </div>
            </div>
        </transition>
        <transition name="g-modal-fade">
            <div class="g-modal-wrapper private" v-show="concatVisible" @click="closeConcat">
                <div class="g-modal user-concat-modal">
                    <div class="g-modal-header user-concat-modal-header">
                        <span>联系我们</span>
                        <i class="iconfont icon-close" @click="closeConcat"></i>
                    </div>
                    <div class="g-modal-content user-concat-modal-content">
                        <div class="user-concat-modal-row">
                            <span class="user-concat-modal-row-label">联系人:</span>
                            <span>张先生</span>
                        </div>
                        <div class="user-concat-modal-row">
                            <span class="user-concat-modal-row-label">手机:</span>
                            <span>13910118699</span>
                        </div>
                        <div class="user-concat-modal-row">
                            <span class="user-concat-modal-row-label">邮箱:</span>
                            <span>zhangjt@geohey.com</span>
                        </div>
                    </div>
                    <div class="g-modal-footer user-concat-modal-footer">
                        <g-button size="large" @click="closeConcat">关闭</g-button>
                    </div>
                </div>
            </div>
        </transition>
    </div>
</template>

<script>
import GInput from '@/components/common/g-input'
import GSelect from '@/components/common/g-dropdown'
import GButton from '@/components/common/g-button'
import { plan as planAPI } from '@/api'

const aliPayAction = '/op/alipay';
// const aliPayAction = '/alipay';

export default {
    name: 'user-plan',
    props: {
        data: {
            default () {
                return {}
            }
        }
    },
    data () {
        return {
            concatVisible: false,
            aliPayAction,
            modalType: 'upgrade',
            modalVisible: false,
            planData: this.$root.geohey.plan,
            voucherChecking: false,
            timeUnitOpions: [
                { key: 'month', name: '按月' },
                { key: 'year', name: '按年' }
            ],
            form: {
                plan: 'free',
                timeUnit: 'month',
                timeCount: 1,
                useVoucher: false,
                voucherId: '',
                discount: 0,
                amount: 0
            },
            payType: '支付宝支付'
        }
    },
    filters: {
        fixed2 ( val ) {
            if ( !isNaN( val ) ) {
                return val.toFixed( 2 ) > 0 ? val.toFixed( 2 ) : 0;
            }
            return 0;
        }
    },
    watch: {
        'form.plan' () {
            this.updateAmount();
        },
        'form.timeUnit' () {
            this.updateAmount();
        },
        'form.timeCount' () {
            this.updateAmount();
        },
        'form.discount' () {
            this.updateAmount();
        },
        'form.voucherId' () {
            this.form.discount = 0;
        },
        'form.amount' () {
            if(this.form.amount > 0){
                this.payType = '支付宝支付';
            }else{
                this.payType = '确认支付';
            }
        },
    },
    computed: {
        plan () {

            let data = {};

            this.planData.forEach( item => {
                let name = item.name;
                data[ name ] = {
                    alias: item.alias,
                    storage: Number( item.storage ) === -1 ? '无限制' : item.storage + 'M',
                    georeference: Number( item.georeference ) === -1 ? '无限制' : item.georeference + '条记录/月',
                    api: Number( item.api_call ) === -1 ? '无限制' : item.api_call + '次/月',
                    month_price: item.month_price,
                    year_price: item.year_price
                 }
            } )

            return data;
        },
        currentPlanName () {
            if ( !this.data || !this.data.plan ) return '';
            return this.data.plan.name
        },
        currentPlanAlias () {
            if ( !this.data || !this.data.plan ) return '';
            return this.data.plan.alias;
        },
        endDate () {
            if ( !this.data || !this.data.plan ) return null;
            let date = new Date ( this.data.plan.endAt );
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            return `${ year }-${ month < 10 ? '0' + month : month }-${ day < 10 ? '0' + day : day }`
        },
        planOptions () {

            let allOptions = [ 'standard', 'advanced' ].map( key => {
                return {
                    key,
                    name: this.planData.find( plan => plan.name === key ).alias
                }
            } )

            let options = [];

            allOptions.forEach( item => {
                if ( this.planCompare( item.key ) < 0 ) {
                    options.push( item );
                }
            } )
            return options;

        },
        timeCountOptions () {
            if ( this.form.timeUnit === 'month' ) {
                let options = [];
                for ( let i = 1; i <= 11; i++ ) {
                    options.push( {
                        key: i,
                        name: i + '个月'
                    } );
                }
                return options;
            } else {
                return [ 1, 2, 3 ].map( i => {
                    return {
                        key: i,
                        name: i + '年'
                    }
                } );
            }
        },
        endTime () {

            let start, end;

            if ( this.modalType === 'upgrade' && this.currentPlanName === 'standard' ) {

                end = new Date ( this.data.plan.endAt );

            } else {


                if ( this.modalType === 'renewals' ) {

                    start = new Date ( this.data.plan.endAt );
                    end = new Date ( this.data.plan.endAt );

                } else {

                    start = new Date();
                    end = new Date();

                }

                let unit = this.form.timeUnit;
                let count = this.form.timeCount;

                if ( unit === 'year' ) {

                    end.setFullYear( start.getFullYear() + count );

                } else {

                    end.setMonth( start.getMonth() + count );   // 如果超过11会自动增加年份

                }

                end.setDate( start.getDate() );

            }

            let Y = end.getFullYear();
            let M = end.getMonth() + 1;
            let D = end.getDate();
            let h = end.getHours();
            let m = end.getMinutes();

            M = M < 10 ? '0' + M : M;
            D = D < 10 ? '0' + D : D;
            h = h < 10 ? '0' + h : h;
            m = m < 10 ? '0' + m : m;

            return `${ Y }-${ M }-${ D } ${ h }:${ m }`
        },

        payDisable () {

            if(!this.form.useVoucher){
                return false;
            }else{
                return  !this.form.discount > 0;
            }
        }
    },
    methods: {
        closeConcat () {
            this.concatVisible = false;
        },
        toggleVoucher () {
            this.form.voucherId = '';

            this.form.discount = 0;
        },
        changeUnit () {
            this.form.timeCount = 1;
        },
        planCompare ( name ) {
            if ( !this.data || !this.data.plan ) return -1;
            let value = {
                free: 0,
                standard: 1,
                advanced: 2,
                enterprise: 3
            }
            return value[ this.data.plan.name ] - value[ name ];
        },
        openModal ( type, plan ) {

            if ( type === 'concat' ) {
                this.concatVisible = true;
                return;
            }

            this.modalType = type;
            this.modalVisible = true;
            if ( plan ) {
                this.form.plan = plan;
            } else {
                this.form.plan = this.planOptions[0] ?  this.planOptions[ 0 ].key : null;
            }
            this.updateAmount( false );
        },
        closeModal () {
            this.modalVisible = false;
        },
        afterLeave () {
            this.form = {
                plan: 'free',
                timeUnit: 'month',
                timeCount: 1,
                useVoucher: false,
                voucherId: '',
                discount: 0,
                amount: 0
            }
        },
        checkVoucher () {
            this.voucherChecking = true;
            let promise = planAPI.checkVoucher( this.form.voucherId );
            promise.then( res => {
                if ( res.data.code === 0 ) {
                    this.$message.success( '优惠码有效' );
                    this.form.discount = Number( res.data.data );
                } else {
                    this.$message.error( res.data.msg );
                    this.form.discount = 0;
                }
                this.voucherChecking = false;
            } ).catch( err => {
                this.$message.error( '优惠码验证错误' );
                this.voucherChecking = false;
                this.form.discount = 0;
            } )
        },
        updateAmount ( checkVoucher = true ) {

            if ( !this.modalVisible ) return;

            let amount = 0;

            let unit = this.form.timeUnit;
            let count = this.form.timeCount;
            let product = this.form.plan;

            let currentPlan = this.planData.find( item => item.name === this.currentPlanName )
            let standardPlan = this.planData.find( item => item.name === 'standard' );
            let advancedPlan = this.planData.find( item => item.name === 'advanced' );


            let currentPlanYearPrice = currentPlan.year_price;
            let currentPlanMonthPrice = currentPlan.month_price;

            let standardYearPrice = standardPlan.year_price;
            let standardMonthPrice = standardPlan.month_price;

            let advancedYearPrice = advancedPlan.year_price;
            let advancedMonthPrice = advancedPlan.month_price;

            if ( this.modalType === 'renewals' ) {

                if ( unit === 'year' ) {

                    amount = count * currentPlanYearPrice;

                } else if ( unit === 'month' ) {

                    amount = count * currentPlanMonthPrice;

                }

                this.form.amount = amount - this.form.discount;

            } else if ( this.modalType === 'upgrade' && this.currentPlanName === 'free') {

                if ( unit === 'year') {

                    let price = product == 'standard' ? standardYearPrice : advancedYearPrice;
                    amount = count * price;

                } else if ( unit === 'month' ) {

                    let price = product == 'standard' ? standardMonthPrice : advancedMonthPrice;
                    amount = count * price;

                }

                this.form.amount = amount - this.form.discount;

            } else if( this.modalType == 'upgrade' && this.currentPlanName == 'standard') {

                if ( !checkVoucher ) return;

                planAPI.calc().then( res => {
                    if ( res.data.code === 0 ) {
                        amount = Number( res.data.data );
                        this.form.amount = amount - this.form.discount;
                    } else {
                        this.$message.error( res.data.msg );
                    }

                } ).catch( err => {
                    this.$message.error( '计算差价失败' );
                } )
            }
        },
        submit () {
            this.$refs.form.submit();
        }
    },
    components: {
        GButton,
        GSelect,
        GInput
    }
}
</script>

<style lang="scss">
@import 'common';
.user-plan {

    // @media screen and (max-width: 1000px)

    .user-plan-content {
        min-width: 1100px;
        position: relative;

        .user-plan-info {
            line-height: 60px;
            margin-bottom: 45px;
            padding-bottom: 20px;
            border-bottom: 1px solid $bdGray;

            &::after {
                @include clearfix();
            }

            .user-plan-current {
                float: left;
                width: 180px;

                .user-plan-type {
                    display: inline-block;
                    font-weight: 600;
                    margin-left: 40px;
                }
            }

            .user-plan-date {
                float: left;
                width: 160px;
            }

            .user-plan-actions {
                float: left;
                height: 100%;       
            }

            @media screen and (max-width: 580px) {
                > div {
                    float: static !important;
                    width: 100% !important;
                }

                .user-plan-actions {
                    padding-left: 20px;
                }
            }
        }

        .user-plan-list {

            &::after {
                @include clearfix();
            }

            .user-plan-header {
                width: 120px;
                float: left;

                &::before {
                    content: '';
                    display: block;
                    width: 100%;
                    height: 240px;
                }

                .user-plan-header-item {
                    height: 70px;
                    line-height: 70px;
                    font-size: $fontSizeBase;

                    &:first-child {
                        &::before {
                            content: '';
                            display: block;
                            position: absolute;
                            width: 100%;
                            border-bottom: 1px solid $bdGray;
                        }
                    }

                    &::after {
                        content: '';
                        display: block;
                        position: absolute;
                        width: 100%;
                        border-bottom: 1px solid $bdGray;
                    }
                }
            }

            .user-plan-item {
                width: 20%;
                max-width: 250px;
                float: left;

                &.current {
                    background-color: #f8fafb;

                    .user-plan-item-header-title {
                        color: $dark !important;
                    }
                }

                @media screen and (max-width: 1250px) {
                    .user-plan-item-header,
                    .user-plan-item-info-item {
                        padding-left: 10px !important;
                        padding-right: 10px !important;
                    }
                }

                .user-plan-item-header {
                    padding: 10px 40px 0;
                    height: 240px;

                    .user-plan-item-header-title {
                        font-size: 22px;
                        font-weight: 600;
                        color: $primary;
                    }

                    .user-plan-item-header-desc {
                        margin: 30px 0 10px;
                        height: 60px;
                    }

                    .user-plan-item-header-price {
                        width: 100%;
                        margin-bottom: 15px;

                        .price-title {
                            color: $deepGray;
                            font-weight: 500;
                        }

                        .price-number {
                            font-weight: 500;
                            color: $gray;
                        }
                    }

                    .user-plan-item-button-free {
                        display: inline-block;
                        color: $primary;
                        height: 32px;
                        line-height: 32px;
                        text-align: center;
                    }
                }

                .user-plan-item-info {

                    .user-plan-item-info-item {
                        height: 70px;
                        line-height: 70px;
                        padding: 0 40px;
                        font-size: $fontSizeLarge;
                        // border-bottom: 1px solid $bdGray;
                    }

                }

                .g-button {
                    padding: 0 18px;
                    font-size: $fontSizeBase;
                }
            }

        }

    }

    .user-plan-modal {
        width: 500px;

        @media screen and (max-width: 580px) {
            width: 90%;
        }

        .user-plan-modal-content {
            padding: 20px 40px;

            .user-plan-modal-row {
                line-height: 40px;

                &::after {
                    @include clearfix();
                }

                .g-select {
                    width: 130px;
                }

                .user-plan-modal-row-label {
                    margin-right: 20px;
                }

                .user-plan-modal-end-time {
                    font-size: $fontSizeLarge;
                    font-weight: 500;
                    color: $primary;

                    @media screen and (max-width: 580px) {
                        display: block;
                        // width: 100%;
                    }
                }
                
                .user-plan-modal-voucher {
                    float: right;
                    padding: 5px 0;
                    opacity: 1;

                    > .g-input {
                        width: 120px;
                        float: left;
                    }

                    > .g-button {
                        float: left;
                        margin: 1px 0 1px 10px;
                    }

                    &.voucher-fade-enter-active, &.voucher-fade-leave-active {
                        transition: opacity .2s;
                    }
                    &.voucher-fade-enter, &.voucher-fade-leave-active {
                        opacity: 0;
                    }
                }

                .user-plan-modal-voucher-label {
                    float: right;
                    user-select: none;
                    cursor: pointer;
                    margin-right: 10px;
                }

                .user-plan-modal-price-label {
                    display: inline-block;
                    height: 100%;

                    .user-plan-modal-price {
                        display: inline-block;
                        height: 100%;
                        line-height: 50px;
                        font-size: 22px;
                        color: $warning;
                        font-weight: 600;
                        margin-left: 10px;
                    }
                }

                .user-plan-modal-price-label-discount{
                    float: left;
                }

                .user-plan-modal-price-label-amount{
                    float: right;
                }
            }
        }

        .user-plan-modal-footer {
            text-align: right;
        }
    }

    .user-concat-modal {
        width: 500px;
        @media screen and (max-width: 580px) {
            width: 90%;
        }

        .user-concat-modal-content {
            padding: 20px 40px;

            @media screen and (max-width: 580px) {
                padding: 20px 10px;
            }

            .user-concat-modal-row {
                height: 40px;
                line-height: 40px;

                &::after {
                    @include clearfix();
                }

                .g-select {
                    width: 130px;
                }

                .user-concat-modal-row-label {
                    display: inline-block;
                    width: 60px;
                }

            }
        }

        .user-concat-modal-footer {
            text-align: right;
        }
    }

}
</style>
